import { useStore } from '@/hooks';
import { Button, Form, Dialog, Switch, Input, Table } from '@alifd/next';
import React, { useEffect, useState, useRef } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { TitleGrid, FieldsGrid, ENUMS, toSelectDataSource } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS, observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import ChargeForm from './ChargeForm';
import ChargeDayForm from './ChargeDayForm';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

const SettingSurcharge = ({ modal, company, onCancel, onSubmit }) => {
  const { companySettingStore: store } = useStore();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [surcharge] = useState(() => observable({}));
  const [disable, setDisable] = useState(false);
  const [state, setState] = useState([]);
  const [curCharge, setCurCharge] = useState();
  const [idx, setIdx] = useState(-1);

  const edit = modal[0] === 'edit';

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (JSON.stringify(company) !== '{}') {
      if (company?.surcharge && company?.surcharge?.length) {
        const parsePrice = company.surcharge.map((item) => ({
          time: item.time,
          price: item.prices.RMB,
          name: company.name,
        }));
        setState(parsePrice);
      }
      editCtx.origin = _.cloneDeep(company);
      _.assign(surcharge, company);
      setDisable(true);
    } else {
      _.set(surcharge, 'selectable', false);
      _.set(surcharge, 'type', '1');
    }
    return () => {
      setDisable(false);
      setState([]);
    };
  }, []);

  const columns = [
    {
      title: t`序号`,
      dataIndex: 'id',
      align: 'center',
      cell: (v, i) => <span>{i + 1}</span>,
    },
    {
      title: t`时间段`,
      dataIndex: 'time',
      width: 200,
      align: 'center',
    },
    {
      title: t`费用`,
      dataIndex: 'price',
      width: 200,
      align: 'center',
    },
    {
      title: t`操作`,
      dataIndex: 'name',
      align: 'center',
      cell: (v, i, r) => (
        <>
          <Button type="primary" text onClick={() => setCurCharge(r)}>{t`编辑`}</Button>
        </>
      ),
    },
  ];

  const overrideModel = {
    name: {
      label: t`费用名称`,
      ui: {
        renderer: (v) => <Input value={v} disabled={edit} placeholder="请输入费用名称" />,
        itemProps: { required: true },
      },
    },
    type: {
      label: t`结算类型`,
      text: (v) => ENUMS.type[v],
      ui: {
        renderer: (v) => <TauSimpleSelect disabled={edit} data={toSelectDataSource(ENUMS.type)} value={v} />,
        itemProps: { required: true },
      },
    },
    RMB: {
      label: t`结算金额`,
      ui: {
        renderer: (v, r) => (
          (r.name === '夜间行驶费' || r.name === '假日附加费') ?
            <Table
              hasBorder={false}
              dataSource={state}
              columns={columns}
              onRowClick={(_, index) => setIdx(index)}
            /> :
            <Input value={v} placeholder="请输入结算金额" />
        ),
      },
    },
    consoleSurcharge: {
      label: t`选择平台费用`,
      ui: {
        renderer: (v) => <TauSimpleSelect showSearch disabled={edit} data={toJS(store.surcharges)} value={v} />,
      },
    },
    selectable: {
      label: t`是否可选`,
      ui: {
        renderer: (v) => <Switch size="small" autoWidth checkedChildren="是" unCheckedChildren="否" disabled={disable} checked={v} />,
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    if (name === 'consoleSurcharge') {
      _.set(surcharge, 'name', value);
      _.set(surcharge, 'selectable', store.surchargesMap[value]?.selectable);
      setDisable(store.surchargesMap[value]?.disable);
    }
    if (name === 'name') {
      const currentDisable = toJS(store?.surcharges).find((list) => list.value === value);
      if (currentDisable) {
        setDisable(true);
      } else {
        setDisable(false);
      }
    }
    if (name === 'consoleSurcharge') {
      if (value === '夜间行驶费' || value === '假日附加费') {
        // 使用正则表达式匹配时间格式
        const findSurcharge = store.taurusSurcharges.find((n) => n.name === value);
        if (findSurcharge) {
          const parsePrice = JSON.parse(findSurcharge.extras.price.value);
          const source = parsePrice.map((p) => ({
            price: p.rmb,
            time: p.time,
            name: value,
          }));
          setState(source);
        }
      }
    }
    _.set(surcharge, name, value);
    editCtx.changed[name] = value === _.get(editCtx.origin, name) ? undefined : value;
  };

  const chargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    const { time, price } = values;
    const [time1, time2] = time;
    setState((pre) => {
      const newCharge = [...pre];
      const timeValue = toJS(surcharge).name === '夜间行驶费' ? `${time1}-${time2}` : `${time1}~${time2}`;
      newCharge[idx].time = timeValue;
      newCharge[idx].price = price;
      return newCharge;
    });
    setCurCharge(false);
  };

  const handleOnCancel = () => {
    setState((pre) => {
      const newCharge = [...pre];
      newCharge[idx].time = toJS(surcharge).name === '夜间行驶费' ? `${newCharge[idx].time[0]}-${newCharge[idx].time[1]}` : `${newCharge[idx].time[0]}~${newCharge[idx].time[1]}`;
      return newCharge;
    });
    setCurCharge(false);
  };


  /**
   * @description 提交表单实现修改车辆
   * @param {*} r formData
   */
  const handleSubmit = (__, errors) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: SettingSurcharge.jsx:207 _ errors:', errors);
      return;
    }
    onSubmit?.(surcharge, state);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <>
      <TitleGrid title={t`费用信息`} />
      <Form
        inline
        value={surcharge}
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <FieldsGrid
          formData={surcharge}
          mode={modal[0]}
          columns={1}
          overrideModel={overrideModel}
          fields={['consoleSurcharge', 'name', 'RMB', 'selectable']}
          itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        />

        <DrawerFooter>
          <FromItem>
            <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>

        <Dialog
          visible={!!curCharge}
          onCancel={() => setCurCharge(false)}
          onClose={() => setCurCharge(false)}
          title={t`修改金额`}
          style={{ width: '30%' }}
          footer={null}
        >
          {toJS(surcharge).name === '夜间行驶费' ?
            <ChargeForm
              data={curCharge}
              onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
              onCancel={() => handleOnCancel()}
            /> :
            <ChargeDayForm
              data={curCharge}
              onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
              onCancel={() => handleOnCancel()}
            />
          }
        </Dialog>
      </Form>
    </>
  );
};

export default observer(SettingSurcharge);
